package com.huan.study.prometheus.service;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author huan.fu 2021/3/15 - 上午12:00
 */
@Service
public class OrderService {

    private final AtomicInteger ORDER_CNT = new AtomicInteger(1);

    private BigDecimal AMOUNT = new BigDecimal("0");

    @Autowired
    private MeterRegistry meterRegistry;

    @PostConstruct
    public void init() {
        Executors.newSingleThreadScheduledExecutor()
                .scheduleAtFixedRate(ORDER_CNT::incrementAndGet, 0, 1, TimeUnit.SECONDS);

        Executors.newSingleThreadScheduledExecutor()
                .scheduleAtFixedRate(() -> {
                    AMOUNT = AMOUNT.add(new BigDecimal(10));
                }, 0, 1, TimeUnit.SECONDS);

        Executors.newSingleThreadScheduledExecutor()
                .scheduleAtFixedRate(this::createOrder, 0, 1, TimeUnit.SECONDS);

    }

    public BigDecimal retrieveOrderAmount() {
        return AMOUNT;
    }

    /**
     * 创建订单
     */
    public int createOrder() {
        Counter.builder("order_counter")
                .tag("system", "order")
                .baseUnit("total")
                .description("订单的总数量")
                .register(meterRegistry)
                .increment();

        return ORDER_CNT.get();
    }
}
